
#include "esp32_com.h"
#include <arduino.h>

uint8_t pin[4] = {HAL_BUTTON_1, HAL_BUTTON_2, HAL_BUTTON_3, HAL_BUTTON_4};
uint8_t pre[4] = {HIGH, HIGH, HIGH, HIGH};
uint8_t now[4] = {HIGH, HIGH, HIGH, HIGH};

CallbackFunction pressed_cb = NULL;
CallbackFunction released_cb = NULL;

//===================================================
void esp32_key_init(void) {
  for (int i = 0; i < 4; i++) {
    pinMode(pin[i], INPUT_PULLUP);
  }
}

//===================================================
void esp32_key_pcb(CallbackFunction f) {
  pressed_cb = f;
}
void esp32_key_rcb(CallbackFunction f) {
  released_cb = f;
}

//===================================================
void esp32_key_update(void) {
  for (int i = 0; i < 4; i++) {
    pre[i] = now[i];
    now[i] = digitalRead(pin[i]);
    if (pre[i] == HIGH && now[i] == LOW) {
      //Serial.println("button pressed: ");
      if (pressed_cb != NULL) pressed_cb(i);
    } else if (pre[i] == LOW && now[i] == HIGH) {
      //Serial.println("button released: ");
      if (released_cb != NULL) released_cb(i);
    }
  }
}

//========================================================
void esp32_hal_init(void) {
  //Serial.begin(115200);
  //Serial.println("esp32_hal_init");
  esp32_key_init();
}

//========================================================
void esp32_hal_loop(void) {
  esp32_key_update();
}
